<template>
  <div class="user-management-view">
    <div class="page-header">
      <h1>用户管理</h1>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="filterForm" class="filter-form" @submit.prevent>
        <el-form-item label="用户名">
          <el-input 
            v-model="filterForm.username" 
            placeholder="请输入用户名" 
            clearable 
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.enable" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="filterForm.role" placeholder="请选择角色" clearable>
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.code" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="user-table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddUser">
              <el-icon><Plus /></el-icon> 新增用户
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredUserList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="60" sortable />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="profile.nickName" label="昵称" min-width="120">
          <template #default="{ row }">
            {{ row.profile?.nickName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="profile.email" label="邮箱" min-width="180">
          <template #default="{ row }">
            {{ row.profile?.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              :type="getRoleTagType(role.code)"
              effect="light"
              class="role-tag"
            >
              {{ role.name }}
            </el-tag>
            <el-tag v-if="!row.roles || row.roles.length === 0" type="info">无角色</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'">
              {{ row.enable ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleChangeStatus(row)"
            >
              {{ row.enable ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '新增用户'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userForm.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-switch v-model="userForm.enable" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  Search, 
  Refresh, 
  Plus
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { userApi, User, Role, UserQueryParams } from '../api/user'
import { encrypt, debounce } from '../utils/common'

// 表单引用
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

// 加载状态
const loading = ref(false)

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 角色列表
const roleList = ref<Role[]>([])

// 角色映射表 - 用于方便地转换code和name
const roleMap = ref<Record<string, string>>({})

// 用户列表
const userList = ref<User[]>([])

// 过滤表单
const filterForm = reactive<UserQueryParams>({
  username: '',
  enable: undefined,
  role: undefined
})

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const userForm = reactive({
  id: 0,
  username: '',
  nickName: '',
  email: '',
  roleIds: [] as number[],
  enable: true,
  password: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email' as const, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 根据角色代码获取标签类型
const getRoleTagType = (code: string): string => {
  const typeMap: Record<string, string> = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'USER': 'success',
    'GUEST': 'info'
  }
  return typeMap[code] || 'primary'
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params: UserQueryParams = {
      pageSize: pageSize.value,
      pageNo: currentPage.value
    }
    
    // 添加筛选条件
    if (filterForm.username) {
      params.username = filterForm.username
    }
    
    if (filterForm.enable !== undefined) {
      params.enable = filterForm.enable
    }
    
    if (filterForm.role) {
      params.role = filterForm.role
    }
    
    const res = await userApi.getUserList(params)
    
    if (res && res.code === 200) {
      userList.value = res.data?.pageData || []
      totalCount.value = res.data?.total || 0
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await userApi.getRoleList()
    if (res && res.code === 200) {
      roleList.value = res.data || []
      
      // 构建角色映射表
      const map: Record<string, string> = {}
      roleList.value.forEach(role => {
        map[role.code] = role.name
      })
      roleMap.value = map
      
      console.log('角色列表已加载', roleList.value)
      console.log('角色映射表', roleMap.value)
    } else {
      ElMessage.error('获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 筛选用户列表 - 仅在前端筛选当不能分页加载时使用
const filteredUserList = computed(() => {
  return userList.value
})

// 搜索输入防抖处理
const handleSearchInput = debounce(() => {
  currentPage.value = 1
  fetchUserList()
}, 500)

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.username = ''
  filterForm.enable = undefined
  filterForm.role = undefined
  currentPage.value = 1
  fetchUserList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchUserList()
}

// 每页条数改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUserList()
}

// 新增用户
const handleAddUser = () => {
  isEdit.value = false
  userForm.id = 0
  userForm.username = ''
  userForm.nickName = ''
  userForm.email = ''
  userForm.roleIds = []
  userForm.enable = true
  userForm.password = ''
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (user: User) => {
  isEdit.value = true
  userForm.id = user.id
  userForm.username = user.username
  userForm.nickName = user.profile?.nickName || ''
  userForm.email = user.profile?.email || ''
  userForm.roleIds = user.roles ? user.roles.map(role => role.id) : []
  userForm.enable = user.enable
  userForm.password = ''
  dialogVisible.value = true
}

// 启用/禁用用户
const handleChangeStatus = (user: User) => {
  const action = user.enable ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}用户 "${user.username}" 吗？`,
    `${action}确认`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 更新用户状态
      const res = await userApi.updateUserStatus(user.id, !user.enable)
      
      if (res && res.code === 200) {
        ElMessage.success(`${action}成功`)
        // 重新获取列表
        fetchUserList()
      } else {
        ElMessage.error(`${action}失败`)
      }
    } catch (error) {
      console.error(`${action}用户失败:`, error)
      ElMessage.error(`${action}失败`)
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑用户
          const updateData = {
            enable: userForm.enable,
            profile: {
              nickName: userForm.nickName,
              email: userForm.email
            },
            roleIds: userForm.roleIds
          }
          
          const res = await userApi.updateUser(userForm.id, updateData)
          
          if (res && res.code === 200) {
            ElMessage.success('更新用户成功')
            dialogVisible.value = false
            // 重新获取列表
            fetchUserList()
          } else {
            ElMessage.error('更新用户失败')
          }
        } else {
          // 新增用户
          const createData = {
            username: userForm.username,
            password: encrypt(userForm.password), // 加密密码
            enable: userForm.enable,
            profile: {
              nickName: userForm.nickName,
              email: userForm.email
            },
            roleIds: userForm.roleIds
          }
          
          const res = await userApi.createUser(createData)
          
          if (res && res.code === 200) {
            ElMessage.success('添加用户成功')
            dialogVisible.value = false
            // 重新获取列表
            fetchUserList()
          } else {
            ElMessage.error('添加用户失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
  })
}

// 加载数据
onMounted(async () => {
  loading.value = true
  
  try {
    // 先加载角色列表，再加载用户列表
    await fetchRoleList()
    await fetchUserList()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请刷新重试')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.user-management-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.user-table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.role-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 